<template>
  <div v-loading="loadingSubmit">
    <Header :isGoBack="false">
      <template v-slot:right>
        <div class="test-btn" v-if="paperData.isAnswer">
          <span class="btn-bg ml20">
            <el-button class="button button-border-second" @click="goReadCenter">
              退出
            </el-button>
          </span>
        </div>
        <div class="test-btn" v-else>
          <span>剩余时间: {{ testTime | filterTime }}</span>
          <span class="btn-bg ml20">
            <el-button class="button button-bg-second" @click="submitPaper">交卷</el-button>
          </span>
          <span class="btn-bg ml20">
            <el-button class="button button-border-second" @click="goStudyCenter">
              退出
            </el-button>
          </span>
        </div>
      </template>
    </Header>
    <div class="intelligent-container">
      <div class="intelligent-train">
        <div class="intelligent-train-header w1200 mb20">水平测试 <i v-if="paperData.isAnswer" @click="readCollect"
            :class="[defaultStart ? 'el-icon-star-on' : 'el-icon-star-off']"
            style="color: rgb(241, 209, 149); cursor: pointer;"></i></div>
        <div class="intelligent-train-contain-box">
          <div class="intelligent-train-contain w1200">
            <ReadingQuestion :paperData="paperData"></ReadingQuestion>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import ReadingQuestion from "../components/readingQuestion";
import Header from "@/components/Header";
import { create, addStudentCollectionQuestion, deleteStudentCollectionQuestion,individualVerifyReadPaper } from "@/api/individuationRead.js"
import {
  createReadPaper,
  verifyReadPaper,
  startReadPaper,
  createReadPaperUnit,
} from "@/api/index";
export default {
  data() {
    return {
      defaultStart: false,
      checkedBookData: {},
      paperData: {},
      testData: {},
      testTimeTimer: null,
      testTime: 0,
      testLoading: false,
      questionType: this.$route.query.questionType,
      checkedType: this.$route.query.checkedType,
      submitReminder: true,
      loadingSubmit: false,
      isCategory: false,
      mode: 1,
    };
  },
  components: {
    Header,
    ReadingQuestion,
  },
  methods: {
    readCollect() {
      let data;
      if (this.$route.query.individuationReadCenter) {
        console.log(this.testData);
        data = {
          question_type: this.testData.student_article_question_info_list[0].student_article_question_answer_info_list[0].answer_type - 1,
          // group_id: Number(this.checkedType),
          unit_id: Number(this.checkedType),
          book_id: this.checkedBookData.book_id,
          source_type: 2,
          link_id: this.testData.student_article_question_info_list[0].question_id,
          source: Number(this.$route.query.questionType)==2?0:1,
          is_individ:1
        }
      } else {
        console.log(this.testData);
        data = {
          question_type: this.testData.student_article_question_info_list[0].student_article_question_answer_info_list[0].answer_type - 1,
          unit_id: Number(this.checkedType),
          book_id: this.checkedBookData.book_id,
          source_type: 2,
          link_id: this.testData.student_article_question_info_list[0].question_id,
          source: Number(this.$route.query.questionType)==2?0:1,
          is_individ:0
        }
      }
      if (this.defaultStart == true) {
        deleteStudentCollectionQuestion(data)
          .then(() => {
            this.$message({
              message: '已取消收藏',
              type: 'warning'
            });
            this.defaultStart = false
          })
          .catch(() => {
            console.log("失败");
          });
      } else {
        addStudentCollectionQuestion(data)
          .then((res) => {
            if (res.code == "200") {
              this.$message({
                message: '收藏成功',
                type: 'success'
              });
            }
            this.defaultStart = true
          })
          .catch(() => {
            console.log("失败");
          });
      }
    },
    goStudyCenter() {
      this.$confirm(`测试还未提交，是否退出`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
      })
        .then(() => {
          this.goReadCenter();
        })
        .catch(() => {
          return false;
        });
    },
    openFullScreen() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        loading.close();
      }, 2000);
    },
    goReadCenter() {
      if (this.$route.query.individuationReadCenter) {
        this.$router.push({
          name: "individuationReadCenter",
          query: { groupId: this.checkedType },
        });
      } else {
        this.$router.push({
          name: "readCenter",
          query: this.$route.query,
        });
      }
    },
    setQuestionData(res) {
      if (res.code == 200) {
        res.data.article_question_answer_info_list.forEach((item) => {
          item.studentAnswer = [];
        });
        this.testData = res.data;
        this.paperData = {
          title: res.data.title,
          type: res.data.type,
          id: res.data.question_id,
          isAnswer: false,
          questionList: res.data.article_question_answer_info_list.map(
            (question) => {
              let newTitle = question.title;
              if (res.data.type == 5) {
                if (question.answer_type == 2) {
                  newTitle = "_____";
                } else {
                  newTitle = "";
                }
              }
              // if (res.data.type == 2) {
              //   if (question.answer_type == 2) {
              //     newTitle = newTitle + "_____";
              //   }
              // }
              if (question.answer_type == 2) {
                let index = 1;
                let pos = newTitle.indexOf("_____");
                while (pos !== -1) {
                  newTitle = newTitle.replace(
                    /_{5}/,
                    ` <input class='question-input' autocomplete="off" id='input-${question.question_id}-${index}' onpaste = "return false";></input> `
                  );
                  index++;
                  pos = newTitle.indexOf("_____");
                }
                question.inputNum = index - 1;
              }
              return {
                questionId: question.question_id,
                title: newTitle,
                answerType: question.answer_type,
                answerList: question.article_answer_info_list,
                studentAnswer: [],
                inputNum: question.inputNum,
              };
            }
          ),
        };
        startReadPaper(this.testData.test_id).then((res2) => {
          if (res2.code == 200) {
            this.testTime = this.testData.test_time;
            //   this.testTime = 30;
            this.timerFun();
          }
        });
      } else if (res.code == 405) {
        this.$alert("暂无试题", "提示", {
          confirmButtonText: "确定",
          callback: () => {
            this.goReadCenter();
          },
        });
      }
    },
    getReadPaper() {
      let data = {
        category: this.checkedType,
        mode: this.mode,
        article_question_type: this.questionType,
        source: 1,
        book_id: this.checkedBookData.book_id,
        question_id: this.$route.query.questionId
          ? this.$route.query.questionId
          : null,
      };
      createReadPaper(data).then((res) => {
        this.setQuestionData(res);
      });
    },
    create() {
      let data = {
        // category: this.checkedType,
        unit_id: this.checkedType,
        mode: this.mode,
        article_question_type: this.questionType,
        source: 1,
        book_id: this.checkedBookData.book_id,
        question_id: 0,
        group_id: this.checkedType
      };
      create(data).then((res) => {
        this.setQuestionData(res);
      });
    },
    getReadPaperUnit() {
      let data = {
        unit_id: this.checkedType,
        mode: this.mode,
        article_question_type: this.questionType,
        source: 1,
        book_id: this.checkedBookData.book_id,
        question_id: this.$route.query.questionId
          ? this.$route.query.questionId
          : null,
      };
      createReadPaperUnit(data).then((res) => {
        this.setQuestionData(res);
      });
    },
    timerFun() {
      this.testTimeTimer = setInterval(() => {
        this.testTime--;
        if (this.testTime > 0 && this.testTime <= 10 && this.submitReminder) {
          this.submitReminder = false;
          this.$confirm(`考试即将超时,即将自动交卷`, "提示", {
            confirmButtonText: "立即交卷",
            cancelButtonText: "取消",
            closeOnHashChange: true,
          })
            .then(() => {
              this.postPaper();
              clearInterval(this.testTimeTimer);
            })
            .catch(() => { });
        } else if (this.testTime <= 3) {
          clearInterval(this.testTimeTimer);
          this.postPaper();
          this.$msgbox.close();
        }
      }, 1000);
    },
    submitPaper() {
      let number = 0;
      this.paperData.questionList.forEach((item) => {
        if (item.answerType == 2) {
          item.studentAnswer = [];
          for (let i = 1; i <= item.inputNum; i++) {
            let inputDom = document.getElementById(
              `input-${item.questionId}-${i}`
            );
            item.studentAnswer.push(inputDom.value.trim());
          }
        }
        if (!item.studentAnswer || item.studentAnswer.length == 0) {
          number++;
        }
      });
      this.$confirm(
        `${number > 0 ? "还有" + number + "道题未答，" : ""}
        是否检查完毕，确认提交？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }
      )
        .then(() => {
          this.postPaper();
        })
        .catch(() => {
          return false;
        });
    },
    postPaper() {
      let data = {
        test_id: this.testData.test_id,
        question_type: this.paperData.type,
        use_time: this.testData.test_time - this.testTime,
        check_article_question_info_list: [
          {
            question_id: this.paperData.id,
            question_type: this.paperData.type,
            check_article_question_info_list: this.paperData.questionList.map(
              (question) => {
                if (question.studentAnswer.length == 0) {
                  return {
                    question_id: question.questionId,
                    student_article_answer_info_list: [{}],
                  };
                } else {
                  return {
                    question_id: question.questionId,
                    student_article_answer_info_list:
                      question.studentAnswer.map((answer) => {
                        if (question.answerType == 1) {
                          let data = question.answerList.filter((item) => {
                            return answer == item.answer_id;
                          });
                          return data[0];
                        } else if (question.answerType == 2) {
                          return {
                            answer,
                          };
                        }
                      }),
                  };
                }
              }
            ),
          },
        ],
      };
      this.loadingSubmit = true;
      if (this.$route.query.individuationReadCenter) {
        individualVerifyReadPaper(data)
          .then((res) => {
            this.verifyReadPaper(res)
          })
          .catch(() => {
            this.loadingSubmit = false;
          });
      } else {
        verifyReadPaper(data)
          .then((res) => {
            this.verifyReadPaper(res)
          })
          .catch(() => {
            this.loadingSubmit = false;
          });
      }
    },
    async verifyReadPaper(res) {

      clearInterval(this.testTimeTimer);
      this.loadingSubmit = false;
      if (res.code == 200) {
        this.testData = res.data;
        let questionData = res.data.student_article_question_info_list[0];
        this.paperData = {
          title: questionData.title,
          type: questionData.type,
          id: questionData.question_id,
          isAnswer: true,
          questionList:
            questionData.student_article_question_answer_info_list.map(
              (question) => {
                let newTitle = question.title;
                if (questionData.type == 5) {
                  if (question.answer_type == 2) {
                    newTitle = "_____";
                  } else {
                    newTitle = "";
                  }
                }
                // if (questionData.type == 2) {
                //   if (question.answer_type == 2) {
                //     newTitle = newTitle + "_____";
                //   }
                // }
                return {
                  questionId: question.question_id,
                  title: newTitle,
                  answerType: question.answer_type,
                  answerList: question.article_answer_info_list,
                  isTrue: question.is_true,
                  parse: question.parse,
                  trueAnswer: question.article_answer_info_list.filter(
                    (answer) => {
                      return answer.is_true == 1;
                    }
                  ),
                  studentAnswer: question.student_article_answer_info_list
                    .filter((answer) => {
                      return answer.answer_id || answer.answer;
                    })
                    .map((answer) => {
                      if (question.answer_type == 2) {
                        return answer.answer;
                      } else {
                        return answer.answer_id;
                      }
                    }),
                  verifyAnswer: question.student_article_answer_info_list,
                };
              }
            ),
        };
      }

    },
    studentIsTrue(question) {
      if (question.is_true == 0 || question.is_true == 1) {
        return question.is_true;
      } else {
        let isTrue =
          question.student_article_answer_info_list &&
          question.student_article_answer_info_list.length ==
          question.article_answer_info_list.filter((answer) => {
            return answer.is_true == 1;
          }).length &&
          question.student_article_answer_info_list.every((item) => {
            return item.is_true;
          });
        return isTrue;
      }
    },
  },

  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.isCategory =
      this.$store.getters.categoryBook.filter((item) => {
        return item == this.checkedBookData.book_id;
      }).length > 0;
    if (this.$route.query.individuationReadCenter) {
      this.create()
      return
    }
    if (this.isCategory) {
      this.getReadPaper();
    } else {
      this.getReadPaperUnit();
    }
  },
  beforeDestroy() {
    clearInterval(this.testTimeTimer);
  },
};
</script>